<template>
    <d2-container>


        <el-dialog
                title="订单详情"
                :visible.sync="dialogVisible"
                width="1000px" height='300px'>

                <!-- <div id="printMe" style="width: 910.8px;height:258px;border:solid 1px black">
                    <div style="padding-left:20px;padding-right: 20px;padding-top: 10px">

                    <div style="font-size:12px;font-weight: 5px"><span>校区:{{productOrderOne.school}}</span></div>
                    <div style="font-size:12px;font-weight: 5px;margin-top:5px"><span>学生:{{productOrderOne.student}}</span></div>
                    <div  style="font-size:12px;font-weight: 5px;margin-top:5px">时间:{{productOrderOne.dateText}}</div>

                    <div style="font-size:12px;font-weight: 5px;margin-top:5px"><b>商品列表</b></div>


                        <table style="margin-top: 5px;border: solid black 1px;width: 100%">
                            <tr>
                                <th style="width: 150px">商品名称</th>
                                <th style="width: 150px">数量</th>
                                <th style="width: 150px"> 价格（元）</th>
                            </tr>
                            <tr v-for='item in productOrderOne.products' style="margin-bottom: 10px;">
                                <td width="150px" style="text-align: center">{{item.productName}}</td>
                                <td width="150px" style="text-align: center">{{item.amount}}</td>
                                <td width="150px" style="text-align: center">{{parseFloat(item.total).toFixed(2)}}</td>
                            </tr>
                            <div style="height: 1px;background: black;width: 300%"></div>
                            <tr style="border:solid 10px red;">
                                <td></td>
                                <td></td>
                                <td style="text-align: center">合计:{{productOrderOne.discount + productOrderOne.total}}元</td>
                            </tr>
                            
                        </table>


                        <div style="font-size: 12px;display: block;width: 95%;text-align: right;margin-top: 5px">优惠 : {{productOrderOne.discount}} 元</div>
                        <div style="font-size: 12px;display: block;width: 95%;text-align: right;margin-top: 5px;">总计 : {{productOrderOne.total - productOrderOne.discount}} 元</div>
                        <div  style="margin-top:0px;width: 90%;margin-left: 20px"><b>备注</b>:<span style="font-size:12px">{{productOrderOne.memoOut}}</span></div>
                    </div>
                </div>
 -->
                <div id="printMe" style="width: 910.8px;height:258px;border:solid 1px black;position: relative;">
                    <div>
                    <div style="font-size:24px;font-weight: 10px;text-align: center;border-bottom: solid 1px #cccccc;width: 100%;display: block">{{productOrderOne.school}}收款单</div>
                    <div style="font-size:18px;font-weight: 5px;width: 33%;border-bottom: solid 1px #cccccc;display: inline-block;border-right:solid 1px #cccccc"><span>学生:{{productOrderOne.student}}</span></div>
                     <div style="font-size:18px;font-weight: 5px;width: 33%;border-bottom: solid 1px #cccccc;display: inline-block;border-right:solid 1px #cccccc;color: white"><span>_</span></div>
                    <div style="font-size:18px;font-weight: 5px;width: 33%;border-bottom: solid 1px #cccccc;display: inline-block;"><span>日期:{{productOrderOne.dateText}}</span></div> 

                    <table style="width: 100%;border-collapse: collapse;display: block;font-size: 16px" >
                            <tr style="font-size: 18px;width: 100%;">
                                <th style="width: 36%;border-right:solid 1px black;border-bottom: solid 1px black;padding:0">项目</th>
                                <th style="width: 15%;border-right:solid 1px black;border-bottom: solid 1px black">数量</th>
                                <th style="width: 15%;border-right:solid 1px black;border-bottom: solid 1px black">单价(元)</th>
                                <th style="width: 11%;border-right:solid 1px black;border-bottom: solid 1px black">合计金额(元)</th>
                                <th style="width: 11%;border-right:solid 1px black;border-bottom: solid 1px black">优惠金额(元)</th>
                                <th style="width: 11%;border-right:solid 1px black;border-bottom: solid 1px black">实收金额(元)</th>
                            </tr>
                            <tr v-for='(item, index) in productOrderOne.products' style="margin-bottom: 3px;font-size: 12px">
                                <td style="text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;border-right:solid 1px black;border-bottom: solid 1px black">{{item.productName}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;">{{item.amount}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;">{{item.sellingPrice}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;" v-if='item.amount != undefined'>{{parseFloat(item.total).toFixed(2)}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;" v-if='item.amount != undefined'>0</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;" v-if='item.amount != undefined'>{{parseFloat(item.total).toFixed(2)}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;color:white" v-if='item.amount == undefined'>-</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;color:white" v-if='item.amount == undefined'>-</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;color:white" v-if='item.amount == undefined'>-</td>
                            </tr>
                            
                            
                        </table>
                        <div  style="font-size:16px;font-weight: 5px;width: 50%;text-align: left;border-bottom: solid 1px black;display: inline-block;">优惠:{{productOrderOne.discount}}元</div>
                        <div  style="font-size:16px;font-weight: 5px;width: 49.5%;text-align: left;border-bottom: solid 1px black;display: inline-block;">合计:{{productOrderOne.discount + productOrderOne.total}}元</div>
                       

                        <div  style="font-size:16px;font-weight: 5px;width: 100%;text-align: left;border-bottom: solid 1px black;display: inline-block;">支付方式:{{productOrderOne.payWayText}}</div>
                         <div  style="font-size:16px;font-weight: 5px;width: 100%;text-align: left;border-bottom: solid 1px black;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">备注:{{productOrderOne.memoOut}}</div>

                         <div  style="font-size:16px;font-weight: 5px;width: 33%;text-align: left;display: inline-block;">收款单位(章):</div>
                         <div  style="font-size:16px;font-weight: 5px;width: 33%;text-align: left;display: inline-block;">经办人:{{productOrderOne.agent}}</div>
                         <div  style="font-size:16px;font-weight: 5px;width: 33%;text-align: left;display: inline-block;">缴款人签字:</div>
                     </div>
            </div>
            
            
           
            <span slot="footer" class="dialog-footer">
                <el-button @click='printabc("div")'>打印订单</el-button>
                <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
            </span>
        </el-dialog>

        <el-form :inline="true" :model="productSearch" ref="productSearch">

            <el-form-item label="支付状态：" prop="payStatus">
                <el-select v-model="productSearch.payStatus" placeholder="请选择支付状态">
                    <el-option
                            v-for="item of this.options.payStatusOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="学生" prop="name">
                <el-input v-model="productSearch.name" placeholder="请输入学生姓名"></el-input>
            </el-form-item>

            <el-form-item label="类型"  >
                <el-select
                        v-model="productSearch.category"
                        filterable
                        placeholder="请选择商品类型"
                        :disabled="disabled"
                >
                    <el-option
                            v-for="item in categoryList"
                            :key="item._id"
                            :label="item.name"
                            :value="item._id"
                    ></el-option>
                </el-select>
            </el-form-item>


            <el-form-item label="校区" prop="school" v-if='showSchool'>
                <el-select
                        v-model="productSearch.school"
                        filterable
                        placeholder="请选择校区"
                        @change="schoolSelected"
                        :disabled="disabled"
                >
                    <el-option
                            v-for="item in schoolList"
                            :key="item._id"
                            :label="item.name"
                            :value="item._id"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="searchFormSubmit">
                    <d2-icon name="search"/>
                    查询
                </el-button>
            </el-form-item>

            <el-form-item>
                <el-button @click="resetForm('productSearch')">
                    <d2-icon name="refresh"/>
                    重置
                </el-button>
            </el-form-item>

            <a href="#/main-order">
                <el-button type="primary" style="float:right" icon="el-icon-plus">新建商品订单</el-button>
            </a>
             <a href="#/product-order-batch">
                <el-button type="primary" style="float:right;margin-right: 10px" icon="el-icon-plus">批量购买</el-button>
            </a>
        </el-form>

        <el-table :data="dataList" border style="width: 100%">
            <el-table-column  label="订单商品">
                <template  slot-scope='scope'>
                   <div style="white-space: pre-line;">  {{scope.row.productText}}</div>
                </template>

            </el-table-column>
            <el-table-column prop="school" label="校区"></el-table-column>
            <el-table-column prop="student" label="购买学生"></el-table-column>
            <el-table-column prop="agent" label="经办人"></el-table-column>
            <!-- <el-table-column prop="school" label="购买校区"></el-table-column> -->
            <el-table-column prop="payWay" label="支付方式"></el-table-column>
            <el-table-column prop="payStatus" label="支付状态"></el-table-column>
            <el-table-column prop="total" label="订单金额"></el-table-column>
            <el-table-column prop="discount" label="优惠金额"></el-table-column>
            <el-table-column prop="statusText" label="状态"></el-table-column>
            <!-- <el-table-column prop="buyer" label="购买者"></el-table-column> -->
            <el-table-column prop="createdAt" label="创建日期"></el-table-column>
            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                    <el-button @click="handleClick(scope.row)" type="text" size="small">修改</el-button>
                    <el-button @click="getProductOrderOne(scope.row)" type="text" size="small">查看</el-button>
                    <el-button v-if="scope.row.payStatus=='待支付'" @click="confirmPay(scope.row)" type="text"
                               size="small">确认付款
                    </el-button>
                    <el-button v-if="scope.row.picked" @click="confirmPicked(scope.row)" type="text"
                               size="small">确认领取
                    </el-button>
                     <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>

        </el-table>
        <el-pagination
                background
                layout="total,sizes,prev, pager, next,jumper"
                :page-size="pageSize"
                :current-page="currentPage"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handlerSizeChange"
                @next-click="handleNextPage"
                @prev-click="handlePrevClick"
        ></el-pagination>
    </d2-container>
</template>

<script>
    import request from "@/plugin/axios";
    import {mapState} from "vuex";
    import formatTime from "@/libs/util.formatTime.js"

    export default {
        data() {
            return {
                dialogVisible: false,
                productOrderOne: {discount:0,total:0,school:{}},
                options: {
                    payStatusOption: [
                        {
                            label: '待支付',
                            value: 0
                        },
                        {
                            label: '已支付',
                            value: 1
                        }
                    ]
                },
                showSchool : false,
                productSearch: {
                    payStatus: undefined,
                    name:undefined,
                    school : undefined
                },
                schoolList : [],
                dataList: [],
                total: 100,
                pageSize: 20,
                currentPage: 1,
                refresh : true
            };
        },
        computed: {
            ...mapState('d2admin/user', ['info']),
        },
        methods: {
            printabc(div){
            var PW =  window.open('', '', 'left=0,top=0,width=600,height=848.6,toolbar=0,scrollbars=0,status=0');
            // 获取div中的html内容
            PW.document.write(document.getElementById('printMe').innerHTML);
            PW.document.close();
            PW.focus();
            PW.print();
            PW.close();

            return false;

    },

        schoolSelected(){
            console.log('callls')
            this.productSearch.category = undefined
            this.categoryList = []
            this.getCategoryList()
        },
            getProductOrderOne(scope) {
                let _id = scope._id
                this.dialogVisible = true;
                request({
                    url: "/productOrder/getProductOrderOne",
                    method: "post",
                    data: {id: _id}
                }).then(res => {
                    if (res.code == 200) {
                        let result = [];
                        let response = res.data;
                        let productOrder = response.productOrder;
                        productOrder.forEach((value) => {
                            let temp = {}
                            temp.productName = value.product.name;
                            temp.amount = value.amount;
                            //销售价格
                            temp.sellingPrice = value.product.sellingPrice;
                            temp.buyer = response.buyer == 1 ? '校区' : '学生';

                            temp.agent = response.agent == undefined ? '' : response.agent.name
                            temp.purchaserName = ''
                            if (response.buyer == 1) {
                                temp.purchaserName = response.school.name

                            } else {
                                temp.purchaserName = response.student == null ? '校外学生' : response.student.name
                            }
                            temp.total = temp.amount * temp.sellingPrice 
                            temp.createdAt = this.formatDate(res.data.createdAt);
                            temp.payStatus = res.data.payStatus == 0 ? '待支付' : (res.data.payStatus == 1 ? '已支付' : '已取消');
                            result.push(temp)
                        })
                        if (res.data.payWay == 0){
                                 this.productOrderOne.payWayText = '现金'
                            }
                            else if (res.data.payWay == 1){
                                 this.productOrderOne.payWayText = '银行卡'
                            }
                            else if (res.data.payWay == 2){
                                 this.productOrderOne.payWayText = '支付宝'
                            }
                            else if (res.data.payWay == 3){
                                 this.productOrderOne.payWayText = '微信'
                            }
                            if (res.data.payWay == 4){
                                 this.productOrderOne.payWayText = '其他'
                            }
                        while (result.length < 3){
                            result.push({product:{},amount:undefined})
                        }
                        this.productOrderOne.school = this.info.school[0].name
                        this.productOrderOne.products = result
                        this.productOrderOne.total = res.data.total
                        this.productOrderOne.discount = res.data.discount
                        this.productOrderOne.student = res.data.student == null ? '校外学生' : res.data.student.name
                        this.productOrderOne.dateText = formatTime.formatTime(res.data.createdAt)
                        this.productOrderOne.payStatusText = res.data.payStatusText == 0 ? '未支付' :'已支付'
                    }
                })
            },
            searchFormSubmit() {
                this.productSearch.page = this.currentPage;
                this.productSearch.pageSize = this.pageSize;
                this.getDataList(this.productSearch);
            },
            resetForm(formName) {
                // this.$refs[formName].resetFields();
                this[formName] = {}
                this.getDataList(this.productSearch);
            },
            handleClick(e) {
                this.$router.push({path: '/product-order-detail?id=' + e._id})
            },
            deleteClick(e){

                this.$confirm('删除并不会改变库存数量','确定要删除该订单吗？',{
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"

                }).then(()=>{
                    request({
                    url: "/productOrder/deleteProductOrder",
                    method: "post",
                    data: {id: e._id}
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: "删除成功"
                        });
                        this.getDataList(this.productSearch);
                    }
                });
                }).catch(()=>{

                })
                
            },
            confirmPay(e) {
                request({
                    url: "/productOrder/updatePayStatus",
                    method: "post",
                    data: {productOrder: e._id}
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: "确认付款成功"
                        });
                        this.getDataList(this.productSearch);
                    }
                });
            },

            confirmPicked(e) {
                request({
                    url: "/productOrder/confirmPicked",
                    method: "post",
                    data: {productOrder: e._id}
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: "确认领取成功"
                        });
                        this.getDataList(this.productSearch);
                    }
                });
            },
            handleCurrentChange(currentPage) {
                this.currentPage = currentPage
                this.productSearch.page = this.currentPage;
                this.productSearch.pageSize = this.pageSize;
                this.getDataList(this.productSearch);
            },
            handlerSizeChange(pageSize) {
                this.pageSize = pageSize
                this.productSearch.page = this.currentPage;
                this.productSearch.pageSize = this.pageSize;
                this.getDataList(this.productSearch);
            },
            handleNextPage() {
                this.currentPage = this.currentPage + 1
                this.productSearch.page = this.currentPage;
                this.productSearch.pageSize = this.pageSize;
                this.getDataList(this.productSearch);
            },
            handlePrevClick() {
                this.currentPage = this.currentPage - 1
                this.productSearch.page = this.currentPage;
                this.productSearch.pageSize = this.pageSize;
                this.getDataList(this.productSearch);
            },
            getSchoolList() {

                let data = {};
                data.page = 1
                data.pageSize = 999999
                request({
                    url: "/school/getSchoolList",
                    method: "post",
                    data
                }).then(res => {
                    this.schoolList = res.data.school;
                    // 返回数据
                });

            },

            getCategoryList() {
                let data = {};
                data.page = 1
                data.pageSize = 999999
                data.school = this.productSearch.school
                console.log(data,'sdsd')
                request({
                    url: "/productCategory/getProductCategoryList",
                    method: "post",
                    data
                }).then(res => {
                    console.log(res,'dsa0')
                    if (res.code == 200){
                        this.categoryList = res.data.productCategory;
                        this.categoryList.push('')
                        this.categoryList.splice(this.categoryList.length - 1, 1)
                        this.schoolList.push('')
                        this.schoolList.splice(this.schoolList.length - 1, 1)
                    }
                   
                    // 返回数据
                });

            },

            getDataList(data) {
                let datax = {}
                this.school = this.info.school.map(value => value._id);
                // data.school = this.school;
                // data.buyer = 2
                datax.buyer = 2
                datax.school = this.school
                if (this.productSearch.school){
                    datax.school = this.productSearch.school
                }

                let index1 = this.rights.indexOf('root') != -1
                let index2 = this.rights.indexOf('授课老师') != -1
                let index4 = this.rights.indexOf('教务老师') != -1
                let index3 = this.rights.indexOf('教务中心') != -1
                let index5 = this.rights.indexOf('校长') != -1
                index1 = index1 || index5
                index2 = index2 || index4
                if ((!index1) && (!index3)){
                    if (index2){
                        datax.teacher = this.staff == null ? 'unbind' : this.staff
                        delete datax.school
                    }
                }
                if (this.productSearch.category){
                    datax.category = this.productSearch.category
                }
                datax.page = this.currentPage
                datax.pageSize = this.pageSize

                if (data.name != undefined){
                    datax.name = data.name
                }
                if (data.payStatus != undefined){
                    datax.payStatus = data.payStatus
                }

                request({
                    url: "/productOrder/getProductOrderList",
                    method: "post",
                    data: datax
                }).then(res => {
                    this.dataList = []
                    this.dataList = res.data.productOrder
                    this.dataList.forEach((item, index) => {
                        this.dataList[index].buyer = item.buyer === 1 ? '校区' : '学生'
                        this.dataList[index].payWay = item.payWay == 1 ? '现金' :'余额'
                        this.dataList[index].payStatus = item.payStatus == 0 ? '待支付' : '已支付'
                        this.dataList[index].agent = item.agent.name
                        if (item.school) {
                            this.dataList[index].school = item.school.name;
                        } else {
                            item.school = '';
                        }
                        if (item.student) {
                            this.dataList[index].student = item.student.name;
                        } else {
                            item.student = '校外学生';
                        }

                        this.dataList[index].productText = item.productOrder.map(value => {
                            return `${value.product.name} x ${value.amount}`
                        }).join("\n");
                        this.dataList[index].picked = true
                        for (var i = 0 ; i < this.dataList[index].productOrder.length;i++){
                            if (!this.dataList[index].productOrder[i].picked == 0){
                                this.dataList[index].picked = false
                            }
                        }
                        this.dataList[index].createdAt = this.formatDate(item.createdAt);
                        this.dataList[index].statusText = this.dataList[index].status == 0 ? '未分配' : '已分成'
                    });
                    this.total = res.data.total;
                    this.currentPage = res.data.currentPage;
                })
            },
            formatDate(date) {
                date = new Date(date);
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                return [year, month, day].map(this.formatNumber).join("-");
            },
            formatNumber(n) {
                n = n.toString();
                return n[1] ? n : "0" + n;
            },
            reload(){
                    this.rights = this.info.rights.map(function(e){return e.name})
                    this.staff = this.info.staff == undefined ? null : this.info.staff._id
                    this.productSearch.page = this.currentPage;
                    this.productSearch.pageSize = this.pageSize;
                    let index1 = this.rights.indexOf('root') != -1
                    let index2 = this.rights.indexOf('授课老师') != -1
                    let index4 = this.rights.indexOf('教务老师') != -1
                    let index3 = this.rights.indexOf('教务中心') != -1
                    let index5 = this.rights.indexOf('校长') != -1
                    index1 = index1 || index5

                    this.currentPage = 1
                    this.pageSize = 20
                    this.getCategoryList()
                    if (index1 && ((this.info.school[0].headquarter == 2) || (this.info.school[0].headquarter == 1))){
                        this.headquarter = true
                        this.showSchool = true
                        this.getSchoolList()
                        this.productSearch.school = this.info.school[0]._id
                    }

                    this.getDataList(this.productSearch);

                    if (this.$route.query.id != undefined) {
                        let temp = {}
                        temp._id = this.$route.query.id 
                        this.getProductOrderOne(temp)
                    }
            }
        },
        beforeRouteEnter(to,from,next){
            console.log(to.meta.refresh == 'a','tee',to.meta.refresh)
            if (to.meta.refresh == 'a'){
                to.meta.refresh = undefined
                next(v=>{
                v.reload()
                })
            }
            else{
                next()
            }

        },

        created() {

            // this.$navigation.on('forward', (to, from) => {
            //     console.log(from.route.meta,'sds0',from.route.meta.auth,from.route.meta.aaa)
            //     if (from.route.meta.keepAlive == 0){
            //         console.log('hey ')
            //         this.reload()
            //         // from.route.meta.keepAlive = undefined
            //     }
            // })

            this.reload()


        


        }
    };
</script>
